var encryptUtil = require('./encryptUtil');
var md5 = require('js-md5')
const {Base64} = require('js-base64')

let cmMap = new Map();

// 白名单
const preUrl = [
  { url: '/file/upload' },
  { url: '/data/find/imgs' },
  { url: '/data/time' },
  { url: '/file' },
  { url: '/schedule/deployCheck' },
  { url: '/excel/common/import' },
  { url: '/views' },
  { url: '/message/buildNotify'},
  { url: '/message/sendMessages'},
  { url: '/data/save/restApi' },
  { url: '/data/save/poModel' },
  { url: '/git/commit' },
  { url: '/data/saveDocs/restApi' },
  { url: '/data/saveDocs/poModel' }
];

/**
 * 清理超过10秒钟的请求
 */
function gcMap() {
  if (cmMap.size > 1000) {
    cmMap.forEach((value, key) => {
      let time = encryptUtil.decrypt(value, "4a765e7a03db421e85578fc7cd95ccda")
      let mius = new Date().getTime() - Number(time)
        if (mius > 10000) {
          cmMap.delete(key)
        }
    })
  }
}

/**
 * 数据解密
 * @param {内容}} content
 */
function process(req, res) {
  console.log("安全检查开始");
  let result = true

  let flag = false
  if (preUrl.find((item) => req.url.indexOf(item.url) != -1)){
    flag = true;
  }

  if (!flag) {
    // 防重放
    result = cmCheck(req, res)

    if (result) {
      // 参数解密
      decrypt(req)
    }
  }

  return result
}

/**
 * 参数解密
 * @param {*} req
 */
function decrypt(req) {
  if (req.body && req.body.data) {
    req.body = JSON.parse(Base64.decode(encryptUtil.decrypt(req.body.data, "4a765e7a03db421e85578fc7cd95ccda")))
  }
}

/**
 * 防重放检查.
 * @param {*} req 
 */
function cmCheck(req, res) {
  let result = true
  let data,url,cm
  if (req.body && req.body.data) {
    data = req.body.data
  }
  url = req.url
  if (data) {
    cm = md5(data + url)
  } else {
    cm = md5(url)
  }
  if (req.headers.cm !== cm) {
    result = false
  }
  
  if (result) {
    console.log('请求缓存数：' + cmMap.size)
    if (cmMap.has(req.headers.cm)) {
      try {
        let last = encryptUtil.decrypt(cmMap.get(req.headers.cm), "4a765e7a03db421e85578fc7cd95ccda")
        let date = encryptUtil.decrypt(req.headers.cmt, "4a765e7a03db421e85578fc7cd95ccda")
        if (last === date) {
          result = false
        } else {
          let date = encryptUtil.decrypt(req.headers.cmt, "4a765e7a03db421e85578fc7cd95ccda")
          let mius = new Date().getTime() - Number(date)
          if (mius > 1000000) {
            result = false
          } else {
            cmMap.set(req.headers.cm, req.headers.cmt)
          }
        }
      } catch (error) {
        result = false
        console.log(error)
      }
    } else {
      let date = encryptUtil.decrypt(req.headers.cmt, "4a765e7a03db421e85578fc7cd95ccda")
      let mius = new Date().getTime() - Number(date)
      if (mius > 1000000) {
        result = false
      } else {
        cmMap.set(req.headers.cm, req.headers.cmt)
      }
    }
  }

  // 清理缓存请求
  gcMap()

  return result
}

module.exports = {
  process
};
